const redis = require("redis");

const client = redis.createClient({
    host: "192.168.20.130",	//	redis地址
    port: 6379, // 端口号
    password: "11111111",	//	redis密码
    legacyMode: true	//redis4必须有这个，官方文档这么说的不然前面的session存储不进去
})
// 监听连接事件
client.on("connect", error => {
    if (!error) {
        console.log("connect to redis success")
    }
})
// 监听错误事件
client.on("error", error => {
    console.log('------------error: ' + error.message)
    throw new Error(error)
})
//设置redies的储存方法
function setString(key, value, expire) {
    return new Promise((resolve, reject) => {
        client.set(key, value, (error, replay) => {
            if (error) {
                reject("设置失败")
            }
            if (expire) {
                client.expire(key, expire);
            }
            resolve("设置成功")
        });
    })
}
//设置redis的获取的方法
function getString(key) {
    return new Promise((resolve, reject) => {
        if (key) {
            client.get(key, (error, replay) => {
                if (error) {
                    reject(`获取${key}失败`)
                }
                resolve(replay);
            })
        }
    })
}

module.exports = {
    setString,
    getString,
    client
}
